const dotenv = require('dotenv');
dotenv.config(); // 加载环境变量
//配置MongoDB连接
const mongoose = require('mongoose');

console.log(process.env.MONGODB_URI);

// 带调试的加强版连接配置
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI, {
    //   useNewUrlParser: true,
    //   useUnifiedTopology: true,
      serverSelectionTimeoutMS: 5000, // 5秒超时
      heartbeatFrequencyMS: 3000      // 心跳检测
    });
    console.log(`✅ MongoDB Connected: ${mongoose.connection.host}`);
  } catch (err) {
    console.error(`❌ 致命连接错误: ${err.message}`.red);
    process.exit(1); // 失败时退出进程
  }
};

 mongoose.set('debug', true); 

// 监听关键事件
 mongoose.connection.on('connected', () => console.log('📡 数据库连接保持中...'));
 mongoose.connection.on('error', (err) => console.error('❌ 连接错误:', err));
 mongoose.connection.on('disconnected', () => console.warn('⚠️ 数据库连接断开'));

module.exports = connectDB;